import React, { Component } from 'react';
import { api } from '../until/api';
import PropTypes from 'prop-types';

export default class Records extends Component {
  constructor() {
    super();
    this.state = {
      edit: false
    }
  }

  recordIndex() {
    return (
      <tr>
        <td>{this.props.record.date}</td>
        <td>{this.props.record.title}</td>
        <td>{this.props.record.amount}</td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.toEdit.bind(this)}>编辑</button>
          <button className="btn btn-danger" onClick={this.toDel.bind(this)}>删除</button>
        </td>
      </tr>
    );
  }
  // 编辑和查看状态切换
  toEdit() {
    this.setState({
      edit: !this.state.edit
    })
  }
  // 删除
  toDel(e) {
    e.preventDefault()
    api.delete(this.props.record.id).then(res => {
      this.props.handleDel(this.props.ind);
    }).catch(err => console.log(err.message))
  }
  // 编辑状态
  recordEdit() {
    return (
      <tr>
        <td><input type="text" className="form-control" defaultValue={this.props.record.date} ref='date'/></td>
        <td><input type="text" className="form-control" defaultValue={this.props.record.title} ref='title'/></td>
        <td><input type="text" className="form-control" defaultValue={this.props.record.amount} ref='amount'/></td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.toSubmit.bind(this)}>提交</button>
          <button className="btn btn-danger" onClick={this.toCancel.bind(this)}>取消</button>
        </td>
      </tr>
    );
  }
   // 编辑状态提交
  toSubmit(event) {
    event.preventDefault();
    this.toEdit()
    const record = {
      date: this.refs.date.value,
      title: this.refs.title.value,
      amount: Number.parseInt(this.refs.amount.value, 0)
    }
    api.updata(this.props.record.id, record).then(
      response => {
        this.setState({edit: false})
        this.props.handleEditRecord(this.props.ind, response.data);
      }
    ).catch(
      error => console.log(error.message)
    )
  }
  // 编辑状态取消
  toCancel() {
    this.toEdit()
  }
  render() {
    if (this.state.edit) {
      return this.recordEdit()
    } else {
      return this.recordIndex()
    }
  }
}

Records.propTypes = {
  id: PropTypes.string,
  date: PropTypes.string,
  title: PropTypes.string,
  amount: PropTypes.string,
}
